package au.com.handsunited.utils;

import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;

import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.database.search.TablesDependencyHelper;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;

/**
 * @author Object
 *
 */
public class DatabaseExporter {


    public static void main(String[] args) throws Exception
    {
        // database connection
        Class driverClass = Class.forName("com.mysql.jdbc.Driver");
        Connection jdbcConnection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/handsunited-test", "volunteer", "v0lunt33r");
        IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);

        // partial database export
        QueryDataSet partialDataSet = new QueryDataSet(connection);
        partialDataSet.addTable("AVAILABILITIES");
        partialDataSet.addTable("ENTITIES");
        partialDataSet.addTable("ENTITY_LANGUAGES");
        partialDataSet.addTable("ENTITY_SERVICECATEGORIES");
        partialDataSet.addTable("ENTITY_SKILLS");
        partialDataSet.addTable("GROUP_RELATIONSHIPS");
        partialDataSet.addTable("INVITATIONS");
        partialDataSet.addTable("LANGUAGES");
        partialDataSet.addTable("MESSAGEBOARDS");
        partialDataSet.addTable("MESSAGES");
        partialDataSet.addTable("ORGANISATION_RELATIONSHIPS");
        partialDataSet.addTable("PROJECT_RELATIONSHIPS");
        partialDataSet.addTable("SERVICECATEGORIES");
        partialDataSet.addTable("SKILLS");
        partialDataSet.addTable("USER_RELATIONSHIPS");

        FlatXmlDataSet.write(partialDataSet, new FileOutputStream("dataset.xml"));

        // full database export
        IDataSet fullDataSet = connection.createDataSet();
        FlatXmlDataSet.write(fullDataSet, new FileOutputStream("full.xml"));

        // dependent tables database export: export table X and all tables that
        // have a PK which is a FK on X, in the right order for insertion
        String[] depTableNames =
          TablesDependencyHelper.getAllDependentTables( connection, "X" );
        IDataSet depDataset = connection.createDataSet( depTableNames );
        FlatXmlDataSet.write(depDataset, new FileOutputStream("dependents.xml"));

    }
}